package com.service.healthycode.task;

import com.service.config.utils.*;
import com.service.healthycode.dto.UserDto;
import com.service.healthycode.entity.UserLoginRecords;
import com.service.healthycode.service.FeignMstscUnique;
import com.service.healthycode.service.UserLoginRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.service.config.constant.Constant.USER_INFO;
import static com.service.config.constant.Constant.USER_INFO_HEALTH_CODE;

/**
 * @program: CloudCampusService
 * @description: 定时任务
 * @author: rui
 * @create: 2021-03-30 15:35
 **/
@Component
@Async
@Slf4j
public class ScheduleService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private FeignMstscUnique feginMstscUnique;
    @Resource
    private UserLoginRecordsService userLoginRecordService;


    @Scheduled(cron = "0/2 * * * * ?")
    @Async("taskExecutorConfig")
    public void getLoginUserDispose() throws Exception {
        if (redisUtil.exist(USER_INFO_HEALTH_CODE)) {
            List<UserLoginRecords> userLoginRecordList = new ArrayList<>();
            List list = redisUtil.getList(USER_INFO_HEALTH_CODE);
            redisUtil.delete(USER_INFO_HEALTH_CODE);
            for (Object o : list) {
                Result result = feginMstscUnique.addApiAccount();
                UserDto userDto = JsonXMLUtils.json2obj(o.toString(), UserDto.class);
                UserLoginRecords userLoginRecord = ModelMapperUtil.strictMap(userDto,UserLoginRecords.class);
                userLoginRecord.setUserId(userDto.getId());
                userLoginRecordList.add(userLoginRecord);
                if (result.getCode() == 200) {
                    userLoginRecord.setId(result.getData().toString());
                }else {
                    userLoginRecord.setId(IdUtil.getStringId());
                }
            }
            if (userLoginRecordList.size()>0) {
                userLoginRecordService.insertOrUpdateBatch(userLoginRecordList) ;
            }
        }
    }
}
